//
//  HKDataSource.swift
//  AppArchitectureSwift
//
//  Created by 胡锦涛 on 2019/2/20.
//  Copyright © 2019 胡锦涛. All rights reserved.
//

import UIKit

/// 不带参数函数
typealias HKCellConfigure = (_ cell:Any, _ model:Any, _ indexPath:NSIndexPath) -> Void

class HKDataSource: NSObject,UITableViewDelegate,UITableViewDataSource {
    
    ///数据源
    var dataArray : [Any] = [Any]()
    
    ///Cell重用标识
    var cellIdentifier : String = ""
    
    ///cellConfigure 回调
    var cellConfigure : HKCellConfigure?
    
    ///自定义初始化方法
    convenience init(_ identifier: String, configureBlock configure: @escaping HKCellConfigure) {
        self.init()
        self.cellIdentifier = identifier
        self.cellConfigure = configure
    }
    
    ///添加数据源
    func addDataArray(array:NSArray){
        
        guard array.count > 0 else {
            return
        }
        
        if self.dataArray.count > 0 {
            self.dataArray.removeAll()
        }
        
        self.dataArray += array  //相当于addObjectsFromArray
        
    }
    
    ///返回单个数据模型
    public func modelsAtIndexPath(indexPath:NSIndexPath) -> Any{
        return self.dataArray.count > indexPath.row ? self.dataArray[indexPath.row] : (Any).self as Any
    }
    
    //MARK:TableView代理方法
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.isEmpty ? 0 : self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier, for: indexPath)
        let model = self.modelsAtIndexPath(indexPath: indexPath as NSIndexPath)
        if (self.cellConfigure != nil) {
            self.cellConfigure!(cell, model, indexPath as NSIndexPath)
        }
        return cell
    }
}
